package com.dys.hejiayuncommunity.framework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;

/**
 * @Author: 疾风
 * @ClassName: ResourcesConfig
 * @Description: 通用跨域配置
 * @CreateDate: 2024/12/23
 * @Version: v1.0.0
 */
@Configuration
public class ResourcesConfig {

    @Bean
    public CorsFilter corsFilter() {

        CorsConfiguration configuration = new CorsConfiguration();
        // 1.允许任何来源
        configuration.setAllowedOriginPatterns(Collections.singletonList("*"));
        // 2.设置访问源请求头
        configuration.addAllowedHeader("*");
        // 3.设置访问源请求方法
        configuration.addAllowedMethod("*");
        // 4.允许凭证
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        // 对接口进行跨域配置
        corsConfigurationSource.registerCorsConfiguration("/**", configuration);
        return new CorsFilter(corsConfigurationSource);
    }
}
